﻿import struct,Pluto,codecs,fnmatch,os

def export(baseoffset):
    print fn
    fp=open(fn,'rb')
    tar=codecs.open('%s-%08x.txt'%(fn,baseoffset),'wb','utf_16')
    fp.seek(baseoffset+0x20)
    num=struct.unpack('i',fp.read(4))[0]
    for i in xrange(num):
        tar.write('No.%d\r\n'%i+u'－'*18+'\r\n')
        fp.seek(baseoffset+0x24+i*8+4)
        offset=struct.unpack('i',fp.read(4))[0]+baseoffset+16
        fp.seek(offset)
        string=[]
        while True:
            char=struct.unpack('H',fp.read(2))[0]
            if char==0:
                break
            elif char==10:
                string.append('\r\n')
            else:
                string.append(unichr(char))
        tar.write(''.join(string)+'\r\n'+u'－'*18+'\r\n'*2)
    fp.close()
    tar.close()

fl=Pluto.walk('resources')
for fn in fl:
    if fnmatch.fnmatch(fn,'*.txt'):
        continue
    elif fnmatch.fnmatch(fn,'*.btx'):
        export(0)
    else:
        fp2=open(fn,'rb')
        data=fp2.read()
        if 'BTX\x20' not in data:
            fp2.close()
            os.remove(fn)
            continue
        size=len(data)
        for k in xrange(size):
            fp2.seek(k)
            if fp2.read(4)=='BTX\x20':
                export(k)
        fp2.close()